#include "unistd.h"
#include "sys/stat.h"
#include "common.h"

#include "ufile.h"
using namespace std;

/* functions*/

/* hexdump,done*/
/* hexdump	,continue show when flag is set*/ 
void hexdump(unsigned char *data, int len, int flag)
{
	static int pre = 0, head = 1;
	int i;
	
	if(0 == flag){
		pre = 0; head = 1;
	}
	
	if(head){
		cout<<"Address\t  ";
		for(i = 0; i<16; i++) cout<<hex<<i<<"\t";
		printf("\n%08x  ", 0);
		head = 0;
	}
	
	if(len){
		for(i = 0; i < len; i++){
			if((pre + i)%16 == 0 && (pre + i) > 0)
				printf("\n%08x  ", int((pre + i)/16));
			printf("%02x\t", data[i]);
		}
		pre += len;
	}
}

/* skip space and tab, done*/
const char *ignoreST(const char *str)
{
	int index = 0;

	while(*(str + index) != '\0')
	{
		if(*(str + index) == ' ' || *(str + index) == '\t')
		{
			index++;
			continue;
		}
		return strdup(str + index);
	}
	return NULL;
}

/* get configure from fname by key*/
const char *get_conf(const char *fname, const char *key)
{
	int size = 128;
	int len;
	char buf[64] = {0};
	FILE *fp = fopen(fname, "r");
	int key_len = strlen(key);

	if(NULL == fp)
	{
		debug("[%s:%d]open file [%s] failed.\n", __FILE__, __LINE__, fname);
		return NULL;
	}
	while(fgets(buf, size, fp))
	{
		len = strlen(buf);
		if(len < 3)
			continue;
		if('\n' == buf[len - 1])
		{
			if('\r' == buf[len -2])
				buf[len - 2] = '\0';
			else
				buf[len - 1] = '\0';
		}
		if('\r' == buf[len - 1])
			buf[len - 1] = '\0';
		if('#' == buf[0])
			continue;
		if(0 == strncmp(buf, key, key_len))
		{
			return ignoreST(buf + key_len);
		}
	}
	return NULL;
}